package com.resou.reader.search.search2;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.resou.reader.R;
import com.resou.reader.bookshelf.readhistory.datasupport.SearchHistory;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class SearchHistoryAdapter extends RecyclerView.Adapter<SearchHistoryAdapter.SearchHistoryHolder> {

    private List<SearchHistory> mSearchHistories;

    public void setSearchHistories(List<SearchHistory> searchHistories) {
        mSearchHistories = searchHistories;
        notifyDataSetChanged();
    }

    SearchHistoryInteractionListener mInteractionListener;

    public void setInteractionListener(SearchHistoryInteractionListener interactionListener) {
        mInteractionListener = interactionListener;
    }

    @NonNull
    @Override
    public SearchHistoryHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        return new SearchHistoryHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.search_history_item, viewGroup, false));
    }

    @Override
    public void onBindViewHolder(@NonNull SearchHistoryHolder searchHistoryHolder, int i) {
        String text = mSearchHistories.get(i).getHistory();
        searchHistoryHolder.historyItemText.setText(text);
        searchHistoryHolder.itemView.setOnClickListener(v -> mInteractionListener.onItemClicked(text));
    }

    @Override
    public int getItemCount() {
        return mSearchHistories == null ? 0 : mSearchHistories.size();
    }

    public void clear() {
        if (mSearchHistories != null) {
            mSearchHistories.clear();
            notifyDataSetChanged();
        }
    }

    class SearchHistoryHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.history_item_text)
        TextView historyItemText;
        @BindView(R.id.history_item_group)
        FrameLayout historyItemGroup;

        public SearchHistoryHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    interface SearchHistoryInteractionListener {
        void onItemClicked(String text);
    }
}
